package com.javasea.scene.repeatSubmit.example2.lock;

import com.javasea.scene.repeatSubmit.config.result.ResultModel;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @Author hhl
 * @Date 2020/11/10 0010 18:41
 * @Version 1.0
 */
@Slf4j
@Aspect
@Component
public class AspectSubmit {
    private static final Logger LOGGER = LoggerFactory.getLogger(AspectSubmit.class);

    @Autowired
    private RedisLock redisLock;

    @Pointcut("@annotation(noRepeatSubmit)")
    public void pointCut(NoRepeatSubmit noRepeatSubmit) {
    }

    @Around("pointCut(noRepeatSubmit)")
    public Object around(ProceedingJoinPoint pjp, NoRepeatSubmit noRepeatSubmit) throws Throwable {
        int lockSeconds = noRepeatSubmit.lockTime();

        HttpServletRequest request = RequestUtils.getRequest();
        Assert.notNull(request, "request can not null");

        String token = request.getHeader("Authorization");
        String path = request.getServletPath();

        int scope = noRepeatSubmit.scope();
        String key;
        if(scope == 0){
            key = getKey(token, path);
        } else if (scope == 1){
            key = pjp.getTarget().getClass().getSimpleName() + path;
        } else {
            return ResultModel.error("@NoRepeatSubmit的scope值异常：scope为：[{}]", scope);
        }

        String clientId = getClientId();
        log.warn("加锁的key为：key[{}]", key);
//        boolean isSuccess = redisLock.tryLock(key, clientId, lockSeconds);
        boolean isSuccess = redisLock.tryLock2(key, clientId, lockSeconds);
        if (isSuccess) {
            // 获取锁成功
            Object result;
            try {
                // 执行进程
                result = pjp.proceed();
                log.warn("执行完毕");
            } finally {
                // 解锁
                log.warn("解锁，key: [{}]", key);
                redisLock.releaseLock(key, clientId);
            }
            return result;
        } else {

            // 获取锁失败，认为是重复提交的请求
            log.warn("表单已提交，请稍后");
            return ResultModel.error("表单已提交，请稍后");
        }
    }
    private String getKey(String token, String path) {
        return token + path;
    }

    private String getClientId() {
        return UUID.randomUUID().toString();
    }
}
